<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="数学建模算法7-一维二维插值以及拟合, python,machine learning,deep learning,html,css,c,c++,cpp,cmake,ros,linux,ubuntu">
    <meta name="description" content="本文主要介绍了数学建模中常见的算法（数据处理方法）：插值以及拟合">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>数学建模算法7-一维二维插值以及拟合 | JackWang&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.4.2">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size: 100% 100%;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">JackWang&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-book-reader" style="zoom: 0.6;"></i>
      
      <span>博客</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按标签归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按目录归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按日期分类文章</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>



<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">JackWang&#39;s Blog</div>
        <div class="logo-desc">
            
            JackWang的个人博客
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book-reader"></i>
			
			博客
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
                              <span>按标签归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
                              <span>按目录归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
                              <span>按日期分类文章</    span>

                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('抱歉，这篇文章并不想让所有人都看到，请输入授权密码观看')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/300px-Splined_epitrochoid.svg.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">数学建模算法7-一维二维插值以及拟合</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python/">
                                <span class="chip bg-color">Python</span>
                            </a>
                        
                            <a href="/tags/Math-Modeling/">
                                <span class="chip bg-color">Math Modeling</span>
                            </a>
                        
                            <a href="/tags/%E4%B8%80%E7%BB%B4%E4%BA%8C%E7%BB%B4%E6%8F%92%E5%80%BC/">
                                <span class="chip bg-color">一维二维插值</span>
                            </a>
                        
                            <a href="/tags/%E6%8B%9F%E5%90%88/">
                                <span class="chip bg-color">拟合</span>
                            </a>
                        
                            <a href="/tags/Interpolation/">
                                <span class="chip bg-color">Interpolation</span>
                            </a>
                        
                            <a href="/tags/Fitting/">
                                <span class="chip bg-color">Fitting</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%95%B0%E5%AD%A6%E5%BB%BA%E6%A8%A1%E7%AE%97%E6%B3%95/" class="post-category">
                                数学建模算法
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-01-07
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-06-01
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    11 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>本文主要介绍了数学建模中常见的算法（数据处理方法）：插值以及拟合</p>
</blockquote>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/300px-Splined_epitrochoid.svg.png" alt="插值" style="zoom:150%;"></p>
<p>PS：图的含义一组离散数据点在一个外延的插值。曲线中实际已知数据点是红色的；连接它们的蓝色曲线即为插值。</p>
<h1 id="数学建模算法7-一维二维插值以及拟合"><a href="#数学建模算法7-一维二维插值以及拟合" class="headerlink" title="数学建模算法7-一维二维插值以及拟合"></a>数学建模算法7-一维二维插值以及拟合</h1><p>严格意义上来说，和前面介绍的各种算法不同，插值和拟合都是数据处理的手段。而由于这个系列介绍的就是数学建模中常用的知识，包括了常用算法、常用问题和常用技巧，因此也一并介绍。</p>
<p>在数学建模的过程中，经常出现的一类操作就是需要对数据进行补全以及外推。例如下面的例子</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107154114356.png" alt="数据补全的例子" style="zoom: 50%;"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107154218906.png" alt="数据外推的例子" style="zoom: 67%;"></p>
<p>从表象上来看，第一个例子中，我们需要的数据在已有的数据范围内，而第二个例子中我们需要的数据并不在已有的数据范围内，两个问题分别对应<strong>插值</strong>问题和<strong>拟合</strong>问题。其实更一般的，<strong>插值寻求得到函数解析式</strong>而<strong>拟合寻求得到趋势的解析式</strong>。之间的规律。</p>
<p>插值和拟合最大的区别在于，<strong>插值那就一定得过数据点</strong>。拟合，就是要得到<strong>最接近的结果，是要看总体效果，因此不一定过所有的数据点</strong>。例如下面的图中，左边一列是插值而右边的一列是拟合。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/v2-2d00103d6c2813e686caba5917d184c6_r.jpg" alt="插值和拟合的区别"></p>
<p>借用知乎上的回答:</p>
<blockquote>
<p>最小二乘意义下的拟合，是要求拟合函数与原始数据的均方误差达到极小，是一种整体意义的逼近，对局部性质没有要求。而所谓“插值”，就是要在原有离散数据之间“插入”一些值，这就要求插值函数必须通过所有的离散点，插值函数在离散点之外的那些点都相当于“插入”的值。插值有全局插值，也有局部插值（比如分段线性插值），插值误差通常考虑的是逐点误差或最大模误差，插值的好坏往往通过某些局部的性质来体现，比如龙格现象或吉布斯振荡。</p>
<p>作者：李晓<br>链接：<a target="_blank" rel="noopener" href="https://www.zhihu.com/question/24276013/answer/32942153">https://www.zhihu.com/question/24276013/answer/32942153</a><br>来源：知乎<br>著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>
</blockquote>
<h1 id="一、插值"><a href="#一、插值" class="headerlink" title="一、插值"></a>一、插值</h1><p>先来看看一些插值的问题</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107161744700.png" alt="问题一" style="zoom: 67%;"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107161815987.png" alt="问题二" style="zoom: 67%;"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107161844996.png" alt="问题三" style="zoom: 67%;"></p>
<p>这些问题可归结为：已知函数在某区间 (域)内若干点处的值，求函数在该区间（域）内其它点处的值。这种问题适宜用插值方法解决。</p>
<p>因此，将一维插值问题描述为：</p>
<script type="math/tex; mode=display">
已知函数在x_0,x_1,\cdots,x_n处的值y_0,y_1,\cdots,y_n。求简单函数p(x)，使得p(x_i)=y_i</script><p>由于泰勒定理，对于一个足够光滑的函数，可以用一个多项式函数来表示。因此一般将$p(x)$取为多项式。</p>
<p>此外，由范德蒙行列式和克莱姆法则可以证明，使得在$x_0,x_1,\cdots,x_n$处取值$y_0,y_1,\cdots,y_n$的多项式存在且唯一。因此插值问题一定有解，因为至少有一个多项式的解。</p>
<h2 id="1-插值的介绍"><a href="#1-插值的介绍" class="headerlink" title="1. 插值的介绍"></a>1. 插值的介绍</h2><p>关于插值，形象的理解就是在前面所说的，根据已有的数据生成得到已经采集到的数据域内的未采集的数据点。更加严谨的定义见下面百度百科和维基百科的介绍</p>
<blockquote>
<p><strong>From BaiduBaike</strong>：</p>
<p>在离散数据的基础上补插连续函数，使得这条连续曲线通过全部给定的离散数据点。 插值是离散函数逼近的重要方法，利用它可通过函数在有限个点处的取值状况，估算出函数在其他点处的近似值。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107160225083.png" alt="百度百科行对插值的介绍"></p>
<p><strong>From Wikipedia</strong>：</p>
<p>在数学的数值分析领域中，内插，或称插值（英语：Interpolation），是一种通过已知的、离散的数据点，在范围内推求新数据点的过程或方法。求解科学和工程的问题时，通常有许多数据点借由采样、实验等方法获得，这些数据可能代表了有限个数值函数，其中自变量的值。而根据这些数据，我们往往希望得到一个连续的函数（也就是曲线）；或者更密集的离散方程与已知数据互相吻合，这个过程叫做拟合。</p>
<p>与插值密切相关的另一个问题是通过简单函数逼近复杂函数。假设给定函数的公式是已知的，但是太复杂以至于不能有效地进行评估。来自原始函数的一些已知数据点，或许会使用较简单的函数来产生插值。当然，若使用一个简单的函数来估计原始数据点时，通常会出现插值误差；然而，取决于该问题领域和所使用的插值方法，以简单函数推得的插值数据，可能会比所导致的精度损失更大。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107160316529.png" alt="维基百科上对插值的介绍"></p>
</blockquote>
<h2 id="2-常见的插值方法"><a href="#2-常见的插值方法" class="headerlink" title="2. 常见的插值方法"></a>2. 常见的插值方法</h2><h3 id="A-最邻近插值"><a href="#A-最邻近插值" class="headerlink" title="A. 最邻近插值"></a>A. 最邻近插值</h3><p>最邻近插值即指使用最邻近的已采集的数据的值作为需要的点处的值</p>
<h3 id="B-线性插值"><a href="#B-线性插值" class="headerlink" title="B. 线性插值"></a>B. 线性插值</h3><p>线性插值通过已知点计算得到一个线性函数，从而通过线性函数来获得未知点的值</p>
<h3 id="C-样条插值"><a href="#C-样条插值" class="headerlink" title="C. 样条插值"></a>C. 样条插值</h3><p>样条函数指一种特殊的函数，由分段的多项式定义。样条插值即指分区间用多个低次多项式进行拟合</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Parametic_Cubic_Spline.svg/400px-Parametic_Cubic_Spline.svg.png" alt="样条函数的例子"></p>
<h3 id="D-多项式插值"><a href="#D-多项式插值" class="headerlink" title="D. 多项式插值"></a>D. 多项式插值</h3><p>对于$n$个点，选择一个高次的多项式来经过所有点。二次插值、三次差值都是多项式插值的特例。</p>
<h3 id="E-拉格朗日插值（Lagrange-Interpolation）"><a href="#E-拉格朗日插值（Lagrange-Interpolation）" class="headerlink" title="E. 拉格朗日插值（Lagrange Interpolation）"></a>E. 拉格朗日插值（Lagrange Interpolation）</h3><p>拉格朗日插值法（Lagrange Interpolation） 指的是在节点上给出节点基函数，然后通过基函数的线性组合，组合系数为节点函数值的一种插值方法。</p>
<p>例如现在需要对下面的三个点进行插值</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107163405396.png" alt="插值的例子"></p>
<p>虽然我们可以写一个多项式$f(x)=ax^2+bx+c$，然后去通过$(x_1,y_1),(x_2,y_2),(x_3,y_3)$这三个点获得三个式子，然后求解出来$a,b,c$三个系数即可。</p>
<p>然而这样做比较麻烦，因此拉格朗日插值法找到了分别通过$(x_1,y_1),(x_2,y_2),(x_3,y_3)$三个点的基函数，而基函数在其他点处的值为0。例如，通过$(x_1,y_1)$的基函数$f_1(x)$满足$f_1(x_1)=y\land f_1(x_2)=0 \land f_1(x_3)=0$。然后将三个基函数叠加即可。</p>
<p>在具体实操作上则找的是$f_1(x_1)=1\land f_1(x_2)=0 \land f_1(x_3)=0$，这样就可以设表达式是$f_1(x)=a(x-x_2)(x-x_3)$，然后带入$x_1,y_1)$求出$a$即可。</p>
<p>因此对于上面的例子，找到的基函数分别为下面三个：</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107163925815.png" alt="三个基函数"></p>
<p>那么最终通过插值得到的表达式为</p>
<script type="math/tex; mode=display">
f(x)=y_1f_1(x)+y_2f_2(x)+y_3f_3(x)</script><p>进一步，对于$n$个点进行拉格朗日插值法得到的表达式为</p>
<script type="math/tex; mode=display">
f(x)=\sum_{i=0}^n y_i\prod_{j\neq i}\frac{x-x_j}{x_i-x_j}</script><h2 id="3-高次差值的Runge现象"><a href="#3-高次差值的Runge现象" class="headerlink" title="3. 高次差值的Runge现象"></a>3. 高次差值的Runge现象</h2><p>在研究插值问题的初期，所有人都想当然地认为（使用多项式插值的时候）插值多项式的次数越高，插值精度越高。然而Runge 通过对一个例子的研究发现， 上述结论仅仅在插值多项式的次数不超过七时成立；<strong>插值多项式的次数超过七时， 插值多项式会出现严重的振荡现象，称之为Runge现象</strong>。</p>
<p>例如我们下面对$f(x)=\frac 1 {1+25x^2}$从-1到1均匀的采点，然后用一个10次的多项式去拟合的结果。可以看到在中间（-0.2~0.2）拟合的还不错，可是越往两边越离谱，甚至只能保证曲线一定过这个点。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107165257557.png" alt="Runge现象的例子" style="zoom: 67%;"></p>
<p>然而若使用多项式插值，那么由于需要插值的点越来越多，多项式的次数一定会越来越高。因此为了解决龙格现象，使用分段的方式进行插值。即将所有的点分成多个区间，每个区间内用低次多项式进行插值，然后在区间的交界处通过二阶导连续等手段使得多个区间得到的多项式之间连续。例如上面介绍的样条插值。一般来说，为了所取得多项式次数最好少于7。</p>
<p>对上面的式子进行样条插值得到的结果如下：</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107170128557.png" alt="样条插值的结果" style="zoom: 67%;"></p>
<h2 id="4-Python中的插值"><a href="#4-Python中的插值" class="headerlink" title="4. Python中的插值"></a>4. Python中的插值</h2><p>Python中的插值使用SciPy中的interpolate模块完成。</p>
<p>下面的内容主要参考<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/136700122">博客</a>：<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/136700122">https://zhuanlan.zhihu.com/p/136700122</a></p>
<h3 id="A-一维插值"><a href="#A-一维插值" class="headerlink" title="A. 一维插值"></a>A. 一维插值</h3><p>一维插值指的是自变量是一个标量，我们前面举得例子都是一维插值。</p>
<p>一维插值主要使用<code>scipy.interpolate.interp1d</code>类实现，其签名如下</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">scipy</span><span class="token punctuation">.</span>interpolate<span class="token punctuation">.</span>interp1d<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">,</span> kind<span class="token operator">=</span><span class="token string">'linear'</span><span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> copy<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span> bounds_error<span class="token operator">=</span>None<span class="token punctuation">,</span> fill_value<span class="token operator">=</span>nan<span class="token punctuation">,</span> assume_sorted<span class="token operator">=</span><span class="token boolean">False</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中，我们需要关注的有：</p>
<ul>
<li>x，y：需要插值的x和y的值</li>
<li>kind：插值方式，所有可选项为：‘linear’, ‘nearest’, ‘nearest-up’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘previous’, or ‘next’。默认为线性插值</li>
</ul>
<p>注意，该类实现了call方法，因此直接call即可</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> numpy <span class="token keyword">as</span> np
<span class="token keyword">import</span> scipy<span class="token punctuation">.</span>interpolate <span class="token keyword">as</span> scinterp

<span class="token keyword">import</span> matplotlib<span class="token punctuation">.</span>pyplot <span class="token keyword">as</span> plt


x <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span> <span class="token operator">*</span> np<span class="token punctuation">.</span>pi<span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">)</span>
y <span class="token operator">=</span> np<span class="token punctuation">.</span>sin<span class="token punctuation">(</span>x<span class="token punctuation">)</span>

x_a <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">3</span> <span class="token operator">*</span> np<span class="token punctuation">.</span>pi<span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span>
f <span class="token operator">=</span> scinterp<span class="token punctuation">.</span>interp1d<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
y_a <span class="token operator">=</span> f<span class="token punctuation">(</span>x_a<span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>type<span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">)</span>

plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>x_a<span class="token punctuation">,</span> y_a<span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>show<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="B-二维插值"><a href="#B-二维插值" class="headerlink" title="B. 二维插值"></a>B. 二维插值</h3><p>二维插值指的是自变量是一个具有两个分量的向量。虽然我们前面讲的都是一维插值的方法，其实对于二维插值，只需要对两个分量分别进行插值即可，即双xxx插值，例如双线性插值。</p>
<p>Python中实现二维插值主要使用<code>scipy.interpolate.interp2d</code>类实现，其签名如下</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">scipy</span><span class="token punctuation">.</span>interpolate<span class="token punctuation">.</span>interp2d<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">,</span> z<span class="token punctuation">,</span> kind<span class="token operator">=</span><span class="token string">'linear'</span><span class="token punctuation">,</span> copy<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span> bounds_error<span class="token operator">=</span><span class="token boolean">False</span><span class="token punctuation">,</span> fill_value<span class="token operator">=</span>None<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中，需要关注的参数为：</p>
<ul>
<li>x, y：二维的点，要么是类似MATLAB的mesh一样的网格点，要么是两个等长的Numpy数组表示点的x，y坐标。</li>
<li>z：二维点对应的值</li>
<li>kind：插值方法，可选的选项有：‘linear’, ‘cubic’, ‘quintic’</li>
</ul>
<p>最后，一般来说一维插值用样条插值而二维插值用立方插值</p>
<h1 id="二、拟合"><a href="#二、拟合" class="headerlink" title="二、拟合"></a>二、拟合</h1><p>在插值问题中要求得到的函数解析式过所有数据点。然而再很多时候，数据量一大，这个时候插值得到的函数解析式无论怎么样都会很复杂。还有很多时候数据是没有解析式的。而且通过插值得到的函数的龙格现象和吉布斯震荡导致在数值域外的震荡非常大，往往使用插值得到的函数只能确保在数值域内的值可信而对数值域外的值不是非常可信。因此针对这种情况，我们就通过拟合来完成。</p>
<p>拟合的目的在于找出数据间的近似函数，其：</p>
<ol>
<li>拟合函数不一定过所有数据点</li>
<li>插值主要求函数值，而拟合主要求函数关系，从而进行进一步的预测</li>
</ol>
<p>拟合的难点在于两个关键点：</p>
<ol>
<li>拟合曲线的线型选择</li>
<li>线型中参数的计算</li>
</ol>
<p>通常而言，线型的选择依靠专业知识（先验知识）和散点图；而参数的计算，若为线性拟合则用最小二乘法，非线性拟合则用Gauss-Newton迭代法。</p>
<h2 id="1-Python中的拟合"><a href="#1-Python中的拟合" class="headerlink" title="1. Python中的拟合"></a>1. Python中的拟合</h2><p>Python中的拟合主要依靠Numpy、Scipy中的函数</p>
<h3 id="A-多项式拟合"><a href="#A-多项式拟合" class="headerlink" title="A. 多项式拟合"></a>A. 多项式拟合</h3><p>多项式拟合主要使用Numpy中的<code>polyfit</code>函数，其函数签名如下</p>
<pre class="line-numbers language-python"><code class="language-python">numpy<span class="token punctuation">.</span>polyfit<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">,</span> deg<span class="token punctuation">,</span> rcond<span class="token operator">=</span>None<span class="token punctuation">,</span> full<span class="token operator">=</span><span class="token boolean">False</span><span class="token punctuation">,</span> w<span class="token operator">=</span>None<span class="token punctuation">,</span> cov<span class="token operator">=</span><span class="token boolean">False</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中，我们需要关注的为：</p>
<ul>
<li>x, y: 需要拟合的数据的x和y的值</li>
<li>deg：拟合的多项式次数</li>
</ul>
<p>返回值为Numpy中的ndarray，分比为从高到低次的项的系数</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> numpy <span class="token keyword">as</span> np
<span class="token keyword">import</span> matplotlib <span class="token keyword">as</span> mpl
<span class="token keyword">import</span> matplotlib<span class="token punctuation">.</span>pyplot <span class="token keyword">as</span> plt


x <span class="token operator">=</span> np<span class="token punctuation">.</span>linspace<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">2</span> <span class="token operator">*</span> np<span class="token punctuation">.</span>pi<span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span>
y <span class="token operator">=</span> <span class="token number">1.5</span> <span class="token operator">*</span> x
y_noise <span class="token operator">=</span> y <span class="token operator">+</span> np<span class="token punctuation">.</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span>np<span class="token punctuation">.</span>random<span class="token punctuation">.</span>randn<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span>len<span class="token punctuation">(</span>y<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

coeff <span class="token operator">=</span> np<span class="token punctuation">.</span>polyfit<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token operator">=</span>y_noise<span class="token punctuation">,</span> deg<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>

plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y<span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>x<span class="token punctuation">,</span> y_noise<span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>plot<span class="token punctuation">(</span>x<span class="token punctuation">,</span> x <span class="token operator">*</span> coeff<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">+</span> coeff<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
plt<span class="token punctuation">.</span>show<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/image-20220107220729119.png" alt="拟合的结果"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Jack Wang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jackwang0107.github.io/2022/01/07/shu-xue-jian-mo-suan-fa-7-yi-wei-er-wei-cha-zhi-yi-ji-ni-he/">https://jackwang0107.github.io/2022/01/07/shu-xue-jian-mo-suan-fa-7-yi-wei-er-wei-cha-zhi-yi-ji-ni-he/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Jack Wang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python/">
                                    <span class="chip bg-color">Python</span>
                                </a>
                            
                                <a href="/tags/Math-Modeling/">
                                    <span class="chip bg-color">Math Modeling</span>
                                </a>
                            
                                <a href="/tags/%E4%B8%80%E7%BB%B4%E4%BA%8C%E7%BB%B4%E6%8F%92%E5%80%BC/">
                                    <span class="chip bg-color">一维二维插值</span>
                                </a>
                            
                                <a href="/tags/%E6%8B%9F%E5%90%88/">
                                    <span class="chip bg-color">拟合</span>
                                </a>
                            
                                <a href="/tags/Interpolation/">
                                    <span class="chip bg-color">Interpolation</span>
                                </a>
                            
                                <a href="/tags/Fitting/">
                                    <span class="chip bg-color">Fitting</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/01/07/shu-xue-jian-mo-suan-fa-8-mo-hu-zong-he-ping-jie-mo-xing/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/v2-368fd890e8f6524b341b070804782bd2_1440w.jpg" class="responsive-img" alt="数学建模算法8-模糊综合评价模型">
                        
                        <span class="card-title">数学建模算法8-模糊综合评价模型</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文主要介绍了数学建模中常见的评价算法（模型）：模糊综合评价
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-01-07
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E5%AD%A6%E5%BB%BA%E6%A8%A1%E7%AE%97%E6%B3%95/" class="post-category">
                                    数学建模算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python/">
                        <span class="chip bg-color">Python</span>
                    </a>
                    
                    <a href="/tags/Math-Modeling/">
                        <span class="chip bg-color">Math Modeling</span>
                    </a>
                    
                    <a href="/tags/%E6%A8%A1%E7%B3%8A%E6%95%B0%E5%AD%A6/">
                        <span class="chip bg-color">模糊数学</span>
                    </a>
                    
                    <a href="/tags/%E6%A8%A1%E7%B3%8A%E7%BB%BC%E5%90%88%E8%AF%84%E4%BB%B7/">
                        <span class="chip bg-color">模糊综合评价</span>
                    </a>
                    
                    <a href="/tags/Fuzzy-Comprehension-Evaluation-Method/">
                        <span class="chip bg-color">Fuzzy Comprehension Evaluation Method</span>
                    </a>
                    
                    <a href="/tags/fuzzy-mathematics/">
                        <span class="chip bg-color">fuzzy mathematics</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/01/06/shu-xue-jian-mo-suan-fa-6-hui-se-guan-lian-fen-xi-yu-yu-ce/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/img/Steps-for-inscribed-cored-grey-relational-analysis-model-IC-GRA-model-calculations.png" class="responsive-img" alt="数学建模算法6-灰色关联分析与预测">
                        
                        <span class="card-title">数学建模算法6-灰色关联分析与预测</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文主要介绍了数学建模中常见的分析与预测算法：灰色关联分析和灰色预测
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-01-06
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E5%AD%A6%E5%BB%BA%E6%A8%A1%E7%AE%97%E6%B3%95/" class="post-category">
                                    数学建模算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python/">
                        <span class="chip bg-color">Python</span>
                    </a>
                    
                    <a href="/tags/Math-Modeling/">
                        <span class="chip bg-color">Math Modeling</span>
                    </a>
                    
                    <a href="/tags/%E7%81%B0%E8%89%B2%E5%85%B3%E8%81%94%E5%88%86%E6%9E%90/">
                        <span class="chip bg-color">灰色关联分析</span>
                    </a>
                    
                    <a href="/tags/%E7%81%B0%E8%89%B2%E9%A2%84%E6%B5%8B/">
                        <span class="chip bg-color">灰色预测</span>
                    </a>
                    
                    <a href="/tags/%E7%81%B0%E8%89%B2%E6%A8%A1%E5%9E%8B/">
                        <span class="chip bg-color">灰色模型</span>
                    </a>
                    
                    <a href="/tags/Grey-relational-analysis/">
                        <span class="chip bg-color">Grey relational analysis</span>
                    </a>
                    
                    <a href="/tags/Grey-Model/">
                        <span class="chip bg-color">Grey Model</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: JackWang&#39;s Blog<br />'
            + '文章作者: Jack Wang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <a href="/about" target="_blank">Jack Wang</a>
            <!-- |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a> -->
            <!-- |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a> -->
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">603.8k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "11";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp"><img src="/medias/icp.png"
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021014294号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackwang0108" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2232123545@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2232123545" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2232123545" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
        
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/libs/others/sakura.js"><\/script>');
            }
        </script>
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
